package pers.zb.center.service.user.api.impl.sys;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import pers.zb.center.common.core.enums.Status;
import pers.zb.center.common.core.service.BaseServiceImpl;
import pers.zb.center.common.core.vo.AjaxResult;
import pers.zb.center.common.core.vo.Pager;
import pers.zb.center.common.core.vo.ZtreeVo;
import pers.zb.center.service.user.api.sys.AppService;
import pers.zb.center.service.user.dao.sys.AppMapper;
import pers.zb.center.service.user.dao.sys.RoleMapper;
import pers.zb.center.service.user.dao.sys.UserRoleMapper;
import pers.zb.center.service.user.entity.sys.SysApp;
import pers.zb.center.service.user.entity.sys.SysRole;
import pers.zb.center.service.user.entity.sys.SysUserRole;
import pers.zb.center.service.user.enums.OnlineStatus;
import pers.zb.center.service.user.qo.sys.AppQo;
import pers.zb.center.service.user.vo.sys.AppVo;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service("appServiceImpl")
public class AppServiceImpl extends BaseServiceImpl<SysApp> implements AppService {

    @Autowired
    private AppMapper appMapper;

    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private UserRoleMapper userRoleMapper;
    
    @Override
    public SysApp getAppByName(String appName) {
        List<SysApp> list = appMapper.getAppByName(appName);
        return (list == null || 0 == list.size()) ? null : list.get(0);
    }

    @Override
    public Pager<AppVo> getList(Pager<AppVo> pager, AppQo appQo) {
        if (pager.getUsePager()) {
            PageHelper.offsetPage(pager.getOffset(), pager.getLimit());
        }
        
        List<AppVo> vos = appMapper.getAppList(appQo, pager);
        pager.setRows(vos);
        PageInfo<AppVo> pageInfo = new PageInfo<AppVo>(vos);
        pager.setTotal(pageInfo.getTotal());
        return pager;
    }

    @Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
    @Override
    public AjaxResult<String> deleteApp(Long appId) throws Exception{
        AjaxResult<String> result = new AjaxResult<String>();
        if (appId == null || "".equals(appId)) {
            result.setCode(10001);
            result.setMsg("appId为空");
            return result;
        }
        SysApp app = appMapper.selectByPrimaryKey(appId);
        if(app.getOnline() == OnlineStatus.YES){
            result.setCode(10002);
            result.setMsg("该应用[" + app.getName() + "]已经上线，不能删除");
            return result;
        }
        if (app == null) {
            result.setMsg("删除成功");
            return result;
        }
        
        //删除应用
        appMapper.delete(app);
        return result;
    }

    @Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
    @Override
    public AjaxResult<String> updateApp(AppQo appQo) throws Exception{
        AjaxResult<String> result = new AjaxResult<String>();

        if (appQo.getAppId() == null || "".equals(appQo.getAppId())) {
            result.setCode(10001);
            result.setMsg("appId为空");
            return result;
        }

        SysApp app = get(appQo.getAppId());
        if (app == null) {
            result.setCode(10002);
            result.setMsg("该应用不存在");
            return result;
        }

        if (StringUtils.isBlank(appQo.getName())) {
            result.setCode(10003);
            result.setMsg("应用名称不能为空");
            return result;
        }
        if (appQo.getStatus() == null) {
            result.setCode(10004);
            result.setMsg("请选择应用状态");
            return result;
        }
        
        
        SysApp sysAppObj = getAppByName(appQo.getName());
        if (sysAppObj != null && !app.getName().equals(sysAppObj.getName())) {//如果是对自身进行编辑更新，就放行
            result.setCode(10006);
            result.setMsg("应用名已经存在");
            return result;
        }
        
        sysAppObj = getAppByCode(appQo.getCode());
        if (sysAppObj != null && !app.getCode().equals(sysAppObj.getCode())) {//如果是对自身进行编辑更新，就放行
            result.setCode(10006);
            result.setMsg("应用编码已经存在");
            return result;
        }
        if(app.getOnline() == OnlineStatus.YES){
            result.setCode(10007);
            result.setMsg("该应用[" + app.getName() + "]已经上线，暂不能进行编辑");
            return result;
        }
        SysApp sysApp = new SysApp();
        sysApp.setId(appQo.getAppId());
        sysApp.setCode(appQo.getCode());
        sysApp.setSort(appQo.getSortNum());
        sysApp.setStatus(appQo.getStatus());
        sysApp.setUpdateTime(new Date());
        sysApp.setName(appQo.getName());
        appMapper.updateByPrimaryKeySelective(sysApp);
        return result;
    }

    
    @Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
    @Override
    public AjaxResult<String> saveApp(AppQo appQo) throws Exception {
        AjaxResult<String> result = new AjaxResult<String>();

        if (StringUtils.isBlank(appQo.getName())) {
            result.setCode(10001);
            result.setMsg("应用名称不能为空");
            return result;
        }

        if (appQo.getStatus() == null) {
            result.setCode(10003);
            result.setMsg("请选择应用状态");
            return result;
        }

        SysApp sysAppObj = getAppByName(appQo.getName());
        if (sysAppObj != null) {
            result.setCode(10006);
            result.setMsg("应用名已经存在");
            return result;
        }
        
        sysAppObj = getAppByCode(appQo.getCode());
        if (sysAppObj != null) {
            result.setCode(10006);
            result.setMsg("应用编码已经存在");
            return result;
        }
        
        SysApp sysApp = new SysApp();
        sysApp.setCode(appQo.getCode());
        sysApp.setSort(appQo.getSortNum());
        sysApp.setStatus(appQo.getStatus());
        sysApp.setUpdateTime(new Date());
        sysApp.setName(appQo.getName());
        sysApp.setCreateTime(new Date());
        sysApp.setIcon(appQo.getIcon());
        sysApp.setOnline(OnlineStatus.NO);
        appMapper.insert(sysApp);
        return result;
    }

    @Override
    @Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
    public AjaxResult<String> deleteApps(Long[] appIdArr) throws Exception {
        AjaxResult<String> result = new AjaxResult<String>();
        if (appIdArr == null || appIdArr.length <= 0) {
            result.setCode(10001);
            result.setMsg("请选择应用");
            return result;
        }
        
        //验证选择的应用中是否有管理员角色的应用
        Example exampleQuery = new Example(SysApp.class);
        exampleQuery.createCriteria().andIn("id",Arrays.asList(appIdArr));
        
        if(appIdArr != null && appIdArr.length > 0){
            for (int i = 0; i < appIdArr.length; i++) {
                //删除应用
                Example example = new Example(SysApp.class);
                example.createCriteria().andIn("id", Arrays.asList(appIdArr));
                appMapper.deleteByExample(example);
            }
        }
        return result;
    }

    @Override
    public SysApp getAppByCode(String code) {
        List<SysApp> list = appMapper.getAppByCode(code);
        return (list == null || 0 == list.size()) ? null : list.get(0);
    }

    @Override
    public List<SysApp> getAllAppForOrderBy(String columnName, String orderType) {
        Example example = new Example(SysApp.class);
        example.setOrderByClause(columnName + " " + orderType);
        return appMapper.selectByExample(example);
    }

    @Override
    public List<SysRole> getRoleListByAppIdUserId(Long appId , Long userId) throws Exception {
        //appid为空的情况下，没有实际业务意义，不然的话查询出来的角色掺杂了很多系统的角色。直接范围null。
        if(appId == null || (appId == null && userId == null)){
            return null;
        }
        
        //获取应用下面的所有角色列表
        if(appId != null && userId == null){
            Example example = new Example(SysRole.class);
            example.createCriteria().andEqualTo("appId", appId);
            return roleMapper.selectByExample(example);
        }
        
        //获取用户在应用下面的角色列表
        if(appId != null && userId != null){
            Example example = new Example(SysUserRole.class);
            example.createCriteria().andEqualTo("userId", userId).andEqualTo("appId", appId);
            List<SysUserRole> userRoleList = userRoleMapper.selectByExample(example);
            
            if(userRoleList != null && userRoleList.size() > 0){
                List<Long> userRoleIds = new ArrayList<Long>();
                for (SysUserRole userRole : userRoleList) {
                    userRoleIds.add(userRole.getRoleId());
                }
                
                Example example2 = new Example(SysRole.class);
                example2.createCriteria().andIn("id", userRoleIds);
                return roleMapper.selectByExample(example2);
            }
        }
        return new ArrayList<SysRole>();//返回一个空集合
    }

    public List<ZtreeVo> queryAllFormatWithZtree(boolean isShowTopParent,List<AppVo> vos) {
        List<ZtreeVo> results = new ArrayList<ZtreeVo>();
        if(isShowTopParent){
            ZtreeVo result = new ZtreeVo();
            result.setId("-1");
            result.setpId("0");
            result.setName("全部");
            results.add(result);
        }

        if (CollectionUtils.isNotEmpty(vos)) {
            for (AppVo vo : vos) {
                ZtreeVo foo = new ZtreeVo();
                foo.setId(String.valueOf(vo.getId()));
                foo.setpId(String.valueOf(-1));
                foo.setName(vo.getName());
                results.add(foo);
            }
        }
        return results;
    }
}
